package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;

import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * DishFlavor控制层
 *
 * @author panda
 * @since 2023/1/1 16:21
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private IDishService dishService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<DishDto> save(@RequestBody DishDto dishDto) {
        log.info("菜品口味对象:{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        /**
         * 在保存新的菜品的时候将redis中的缓存删除掉,保持缓存的一致性
         */
        String key = "dish:" + dishDto.getCategoryId() + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success(dishDto);
    }

    /**
     * 菜品分页展示界面
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getPage(Integer page, Integer pageSize, String name) {

        log.info("page:{}----pageSize:{}----name:{}", page, pageSize, name);

        //先把分页的原始数据拿到
        //构建分页对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //再使用条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //获取原生的分页数据
        dishService.page(dishPage, queryWrapper);
        //但是现在还没有口味flavor的相关信息categoryName,菜品分类名称
        //需要将dish复制到dishDto中
        //这个是记录
        List<Dish> dishList = dishPage.getRecords();
        //这个是总条数
        long dishPageTotal = dishPage.getTotal();
        //先构建分页对象
        Page<DishDto> pageDto = new Page<>();
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //将一条条记录加在里面
            dishDtoList.add(dishDto);
            //但是此时记录中仍然没有categoryName,菜品分类名称
            //需要使用MP中的categoryService查询的方式将categoryName查询出来
            Category categoryById = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(categoryById.getName());
        }
        pageDto.setRecords(dishDtoList);
        pageDto.setTotal(dishPageTotal);

        return R.success(pageDto);
    }

    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        log.info("根据的id获取菜品===>{}", id);
        //调用dishService的方法,返回菜品的信息,但是一定要带有dishFlavor口味的信息
        DishDto dishDto = dishService.findIdWithFlavor(id);

        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateWithSave(@RequestBody DishDto dishDto) {
        log.info("修改保存的菜品信息===>{}", dishDto);
        dishService.updateWithFlavor(dishDto);
        /**
         * 在更新的时候将redis中的缓存删除掉,保持缓存的一致性
         */
        Set keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    //@GetMapping("/list")
    //public R<List<Dish>> listByCategoryId(Long categoryId) {
    //    log.info("菜品名称为===>{}",categoryId);
    //    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    //    queryWrapper.eq(Dish::getCategoryId, categoryId);
    //    List<Dish> dishList = dishService.list(queryWrapper);
    //    return R.success(dishList);
    //
    //}
    /**
     * 导入代码
     */
    @Autowired
    private IDishFlavorService dishFlavorService;

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        /**
         * 使用redis优化,完成在一开始进入页面时的缓存优化
         * 在进入到页面时,先进行在redis中查询缓存,有的话就不在进行数据库的查询动作,
         * 优化查询速度,使用redis提升性能
         */
        //在进入到首页面访问时,优先进行redis的缓存进行查询
        //设计redis缓存中键的值
        List<DishDto> redisDishDto = null;
        String key = "dish:" + dish.getCategoryId() + dish.getStatus();
        redisDishDto = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (redisDishDto != null) {
            log.info("从reids读取分类下的菜品信息");
            return R.success(redisDishDto);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（在售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());
        //将查询出的菜品放入到redis当中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}